﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace ParticleFiltersDemo1
{
    public class ParticlesSet
    {
        /* 
         * Cluster coordinates
         */ 
        public double meanX; 
        public double meanY;

        private int particlesCount;
        private Board board;

        public ParticlesSet( int count, Board board )
        {
            this.IsDone = false;
            this.Particles = new Particle[count];
            this.particlesCount = count;
            this.board = board;            
        }
                
        /*
         * Have we found our coordinates?
         */ 
        public bool IsDone 
        {
            get;
            private set;
        }

        public Particle[] Particles
        {
            get;
            set;
        }

        public void InitializeParticles()
        {
            int i;

            for ( i = 0; i < this.particlesCount; i++ )
            {
                int[] res = this.board.GetRandomFreeCell();
                Particle p = new Particle( ( double )res[0], ( double )res[1], 1, true, board );
                Particles[i] = p;
            }
        }

        /*
         * Computing the coordinads of the mean point and if we've finished searching location
         */
        public void ComputeMeanPoint( Board board )
        {
            double weightSum = 0;
            double mean_x = 0;
            double mean_y = 0;
            for ( int i = 0; i < Particles.Length; i++ )
            {
                Particle p = Particles[i];
                weightSum += p.weight;
                mean_x += p.X * p.weight;
                mean_y += p.Y * p.weight;
            }
            if ( weightSum == 0 )
            {
                meanX = -1;
                meanY = -1;
                IsDone = false;
                return;

            }
            mean_x /= weightSum;
            mean_y /= weightSum;
            int mCount = 0;
            for ( int i = 0; i < Particles.Length; i++ )
            {
                Particle p = Particles[i];
                if ( Math.Sqrt( ( p.X - mean_x ) * ( p.X - mean_x ) - ( p.Y - mean_y ) * ( p.Y - mean_y ) ) < 1 )
                {
                    mCount++;
                }
            }
            if ( mCount > Particles.Length * 0.95 )
            {
                IsDone = true;
            }

            meanX = mean_x;
            meanY = mean_y;
        }
    }
}
